<?php
 
declare(strict_types=1);
 
namespace app\controller;

use app\services\JwtService;
use Exception;
use think\worker\Server;
use \think\facade\Db;

/**
 * WebSocket 服务工作类
 */
class Worker extends Server
{
    /**websocket */
 
    protected $socket = 'websocket://0.0.0.0:23567';
 
    /**定义测验组*/
    protected $discussArr = [];
 
    /*
    @method 		发送消息
    @param          data              数据
    */
    public function onMessage($connection, $data)
    {
        /**对接收消息做json处理*/
        $rest                = json_decode($data);
        // 权限处理
        try{
            $jwt = new JwtService;
            $userInfo = $jwt->checkToken($rest->Authorization);
        }catch(Exception $e){
            $connection->send(json_encode(['status'=>'fail','type' => 'connection','msg'=>'身份验证失败']));
            return;
        }
        try{
            if($userInfo->user->desc == 'teacher'){
                
            }else if($userInfo->user->desc == 'student'){
                
            }else{
                throw "身份验证失败";
            }
        }catch(Exception $e){
            $connection->send(json_encode(['status'=>'fail','type' => 'connection','msg'=>'身份验证失败']));
            return;
        }
        if($rest->type == 'conn'){
            $discussID = $rest->discussID ; 
            $connection->discussID = $discussID;
            // $this->uidArr[$userInfo->user->userId] = $connection;
            $this->discussArr[$discussID][$userInfo->user->userId] = $connection;
            $msg = [
                'status' => 'success',
                'type' => 'connection',
                'msg' => '成功连接!'
            ];
            $connection->send(json_encode($msg));
            echo 'conn:'. $userInfo->user->userId.PHP_EOL;
        }else{
            if(!isset($connection->discussID)){
                $connection->send(json_encode(['status'=>'fail','type' => 'connection','msg'=>'错误的链接']));
                return;
            }
            try{
                if($userInfo->user->desc == 'student'){
                    $result = Db::name("studentdiscuss")->insert([
                        'SID'=> $userInfo->user->userId,
                        'content'=> $rest->msg,
                        'updateTime' => date("Y-m-d H:i:s",time()),
                        'discussID' => $connection->discussID
                    ]);
                    if(!$result){
                        throw "保存失败";
                    }
                }else{
                    $result = Db::name("teacherdiscuss")->insert([
                        'TID'=> $userInfo->user->userId,
                        'content'=> $rest->msg,
                        'updateTime' => date("Y-m-d H:i:s",time()),
                        'discussID' => $connection->discussID
                    ]);
                    if(!$result){
                        throw "保存失败";
                    }
                }
            }catch(Exception $e){
                echo $e;
                $connection->send(json_encode(['status'=>'fail','type' => 'connection','msg'=>'评论失败']));
                return;
            }
            $msg = [
                'status' => 'success',
                'type' => 'message',
                'msg' => [
                    'name' => $userInfo->user->username ,
                    'ID' => $userInfo->user->userId ,
                    'msg' => $rest->msg ,
                    'time' => time(),
                ]
            ];
            //$connection -> send(json_encode($msg));
            foreach($this->discussArr[$connection->discussID] as $client){
                $client-> send(json_encode($msg));
            }
        }

    }
 
 
    /**
     * 当连接建立时触发的回调函数
     * @param $connection
     */
    public function onConnect($connection)
    {
        echo '连接成功'.PHP_EOL;
    }
 
 
    /**
     * 当连接断开时触发的回调函数
     * @param $connection
     */
    public function onClose($connection)
    {
        //print_r('用户断开了链接！');
        echo '用户断开了链接！'.PHP_EOL;
    }
 
 
    /**
     * 当客户端的连接上发生错误时触发
     * @param $connection
     * @param $code
     * @param $msg
     */
    public function onError($connection, $code, $msg)
    {
        echo "error $code $msg\n";
    }
 
    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {
    }
}